//
//  GYStoreResultViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/15.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

static NSString *HorCellIdentifier = @"HorCellIdentifier";
static NSString *VerCellIdentifier = @"VerCellIdentifier";
static NSString *HeadViewIdentifier = @"HeadViewIdentifier";
#define COUNT @"20"



#import "GYStoreResultViewController.h"
#import "GYStoreAllHorCell.h"
#import "GYStoreAllVerCell.h"
#import "GYSearchGoos.h"
#import "GYNetWorkTools.h"
#import "GYSortView.h"
#import "GYSortSelectView.h"
#import "GYShopHomeViewController.h"
#import "GYNoAddressView.h"
#import "GYPriceScreenViewController.h"
#import "GYUser.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYSystemMessageViewController.h"
#import "GYShopingCartViewController.h"

@interface GYStoreResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

/** 选择排序方式界面 */
@property (nonatomic, weak) GYSortSelectView *selectView;

/** 排序视图 */
@property (nonatomic, strong) GYSortView *sortView;

/** 表示商品排列方式 */
@property (nonatomic, getter=isLayout) BOOL layout;

/** <#descrption#> */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *goodsList;

//是否还有更多数据
@property (nonatomic, getter=isHasmore) BOOL hasmore;

/** 当前数据页数 */
@property (nonatomic, assign) NSInteger currentPage;

/** 记载当前数据的排布格式 */
@property (nonatomic, strong) NSString *key;

/** 数据顺序 */
@property (nonatomic, strong) NSString *order;

/** 没有商品的视图 */
@property (nonatomic, strong) GYNoAddressView *searchInfoView;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

@end

@implementation GYStoreResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBColor(245, 245, 245);
    self.currentPage = 1;
    self.key = @"1";
    self.order = @"1";
    self.hasmore = YES;
    
    //初始化
    [self setupUI];
    
    //初始化视图
    [self setupCollectionView];
    
    //加载视图
    [self creatNoSearchResultInfoView];
    
    //加载全部商品数据
    [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:COUNT stc_id:@"" keyword:self.keyworld key:@"1" order:@"1" price_from:@"" price_to:@""];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.selectView.frame = CGRectMake(0, 0, ScreenWidth, 50);
    self.collectionView.frame = CGRectMake(0, 50, ScreenWidth, ScreenHeight-64-50);
}

//创建没有搜索结果的UI
- (void)creatNoSearchResultInfoView {
    GYNoAddressView *searchInfoView = [[[NSBundle mainBundle]loadNibNamed:@"GYNoAddressView" owner:nil options:nil]firstObject];
    searchInfoView.frame = CGRectMake(0, 50, ScreenWidth, ScreenHeight-64-50);
    searchInfoView.markImageView.image = [UIImage imageNamed:@"search_w"];
    searchInfoView.headLable.text = @"没有找到任何相关信息";
    searchInfoView.footLable.text = @"选择搜索其他商品名称或筛选项...";
    [searchInfoView.addBtu setTitle:@"查看全部商品" forState:UIControlStateNormal];
    searchInfoView.hidden = YES;
    __weak typeof(self) weakSelf = self;
    searchInfoView.addNewAddressCallBack = ^{
        //重新加载数据
        [weakSelf.goodsList removeAllObjects];
        weakSelf.currentPage = 1;
        weakSelf.hasmore = YES;
        [weakSelf loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:COUNT stc_id:@"" keyword:self.keyworld key:@"1" order:@"1" price_from:@"" price_to:@""];
    };
    [self.view addSubview:searchInfoView];
    self.searchInfoView = searchInfoView;
}

- (void)setupUI {
    //1.设置搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, 130, 40);
    searchBar.backgroundImage = [[UIImage alloc] init];
    UITextField *searchField = [searchBar valueForKey:@"searchField"];
    searchField.layer.borderColor = RGBColor(152, 152, 152).CGColor;
    searchBar.placeholder = @"请输入关键词";
    self.navigationItem.titleView = searchBar;
    
    //2.设置导航栏
    UIBarButtonItem *cateItem = [UIBarButtonItem itemWithImage:@"stiore_categroy_b" tagret:self action:@selector(categoryBtuClick) button:nil];
    UIBarButtonItem *moreItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(moreBtuClick) button:nil];
    self.navigationItem.rightBarButtonItems = @[moreItem,cateItem];

    
    //1.添加排序选择方式
    GYSortSelectView *selectView = [[[NSBundle mainBundle] loadNibNamed:@"GYSortSelectView" owner:nil options:nil] firstObject];
    selectView.selectorModeCallBack = ^(NSInteger tag,UIButton *btu,BOOL layout) {
        switch (tag) {
            case 1:
            {
                if (self.sortView != nil) {
                    self.sortView.hidden = !self.sortView.isHidden;
                }else {
                    self.sortView = [[[NSBundle mainBundle] loadNibNamed:@"GYSortView" owner:nil options:nil] firstObject];
                    self.sortView.frame = CGRectMake(0, 50, ScreenWidth, ScreenHeight-64-50);
                    [self.view addSubview:self.sortView];
                }
                __weak typeof(self) weakSelf = self;
                self.sortView.sortResultCallBack = ^(NSInteger tag,NSString *sortTitle) {
                    //1.隐藏视图
                    weakSelf.sortView.hidden = YES;
                    [btu setTitle:sortTitle forState:UIControlStateNormal];
                    
                    //这里决定这个商品是怎么样排序的;
                    switch (tag) {
                        case 0:
                        {
                            weakSelf.key = @"1";
                            weakSelf.order  = @"2";
                        }
                            break;
                            
                        case 1:
                        {
                            weakSelf.key = @"2";
                            weakSelf.order  = @"2";
                        }
                            break;
                            
                        case 2:
                        {
                            weakSelf.key = @"2";
                            weakSelf.order  = @"2";
                        }
                            break;
                            
                        case 3:
                        {
                            weakSelf.key = @"4";
                            weakSelf.order  = @"2";
                        }
                            break;
                        default:
                            break;
                    }
                    
                    //清楚当前的页数的历史记录
                    weakSelf.currentPage = 1;
                    [weakSelf.goodsList removeAllObjects];
                    
                    //清楚记录是否数据的记录
                    weakSelf.hasmore = YES;
                    
                    //加载数据
                    [weakSelf loadStoreAllGoods:[NSString stringWithFormat:@"%zd",weakSelf.currentPage] page:COUNT stc_id:@"" keyword:weakSelf.keyworld key:weakSelf.key order:weakSelf.order price_from:@"" price_to:@""];
                    
                    
                };
                
            }
                break;
                
            case 2:
            {
                self.currentPage = 1;
                self.hasmore = YES;
                [self.goodsList removeAllObjects];
                self.key = @"3";
                self.order = @"2";
                
                [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:COUNT stc_id:@"" keyword:self.keyworld key:self.key order:self.order price_from:@"" price_to:@""];
            }
                break;
                
            case 3:
            {
                self.layout = layout;
                [self.collectionView reloadData];
            }
                break;
                
            default:
                break;
        }
        
    };
    [self.view addSubview:selectView];
    self.selectView = selectView;
}
#pragma mark -- 按钮点击事件

- (void)categoryBtuClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)moreBtuClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    basePopoverVC.titles = @[@"首页",@"购物车",@"我的商城",@"消息"];
    basePopoverVC.images = @[@"home_w",@"ff_icon3",@"ff_icon4",@"message_w"];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                weakSelf.tabBarController.selectedIndex = 0;
                [weakSelf.tabBarController.tabBar setHidden:NO];
            }
                break;
                
            case 1:
            {
                if ([GYUser loadUserInfo] != nil) {
                    GYShopingCartViewController *shopingCartVC = [[GYShopingCartViewController alloc] initWithNibName:@"GYShopingCartViewController" bundle:nil];
                    [weakSelf.navigationController pushViewController:shopingCartVC animated:YES];
                    
                }else {
                    weakSelf.tabBarController.selectedIndex = 2;
                    [weakSelf.tabBarController.tabBar setHidden:YES];
                }
            }
                break;
                
            case 2:
            {
                weakSelf.tabBarController.selectedIndex = 2;
                [weakSelf.tabBarController.tabBar setHidden:YES];
            }
                break;
                
            case 3:
            {
                if ([GYUser loadUserInfo] != nil) {
                    GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                    [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];
                    
                }else {
                    weakSelf.tabBarController.selectedIndex = 2;
                }
            }
                break;
                
            default:
                break;
        }
    };
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 64, widthScale(130, iphone6_W), 200);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];

}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, ScreenWidth, self.view.height-50) collectionViewLayout:flowLayout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //注册
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreAllHorCell" bundle:nil] forCellWithReuseIdentifier:HorCellIdentifier];
    
    [collectionView registerNib:[UINib nibWithNibName:@"GYStoreAllVerCell" bundle:nil] forCellWithReuseIdentifier:VerCellIdentifier];
    
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeadViewIdentifier];
}

- (void)loadStoreAllGoods:(NSString *)curpage page:(NSString *)page stc_id:(NSString *)stc_id keyword:(NSString *)keyword key:(NSString *)key order:(NSString *)order price_from:(NSString *)price_from price_to:(NSString *)price_to {
    
    if (self.isHasmore) {
        [EasyLodingView showLodingText:@"正在加载..."];
        [GYNetWorkTools requestStoreAllGoods:self.store_id curpage:curpage page:page stc_id:stc_id keyword:keyword key:key order:order price_from:price_from price_to:price_to success:^(NSDictionary *obj) {
            //NSLog(@"obj ========%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            NSDictionary *datas = [obj objectForKey:@"datas"];
            if (code == 200) {
                [EasyLodingView hidenLoding];
                self.currentPage += 1;
                //判断是否在次请求的判断标示
                self.hasmore = [[obj objectForKey:@"hasmore"] boolValue];
                
                NSArray *goods_list = [datas objectForKey:@"goods_list"];
                NSArray *models = [GYSearchGoos loadGoodsData:goods_list];
                [self.goodsList addObjectsFromArray:models];
                
                if (self.goodsList.count == 0) {
                    self.searchInfoView.hidden = NO;
                }else {
                    self.searchInfoView.hidden = YES;
                }
                
                [self.collectionView reloadData];
                
            }else if (code == 400) {
                [EasyTextView showText:@"数据加载出错,请重新加载!"];
                [EasyLodingView hidenLoding];
                NSLog(@"网络数据加载失败...");
            }
        } error:^(NSError *error) {
            [EasyTextView showText:@"数据加载出错,请重新加载!"];
            [EasyLodingView hidenLoding];
            NSLog(@"laodStoreAllGoodsFailed====%@",error);
        }];
    }else {
        [EasyTextView showText:@"没有更多数据了!"];
        NSLog(@"没有数据可以加载了.....");
    }
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayou

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.goodsList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.layout) {
        //纵向
        GYStoreAllVerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:VerCellIdentifier forIndexPath:indexPath];
        cell.model = self.goodsList[indexPath.item];
        
        //判断是否到最底端  判断要加载的数据是按照上面格式排布的数据
        if (indexPath.row == self.goodsList.count - 1) {
            [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:COUNT stc_id:@"" keyword:self.keyworld key:self.key order:self.order price_from:@"" price_to:@""];
        }
        
        return cell;
    }else {
        //横向
        GYStoreAllHorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HorCellIdentifier forIndexPath:indexPath];
        cell.model = self.goodsList[indexPath.item];
        
        //判断是否到最底端  判断要加载的数据是按照上面格式排布的数据
        if (indexPath.row == self.goodsList.count - 1) {
            [self loadStoreAllGoods:[NSString stringWithFormat:@"%zd",self.currentPage] page:COUNT stc_id:@"" keyword:self.keyworld key:self.key order:self.order price_from:@"" price_to:@""];
        }
        
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchGoos *model = self.goodsList[indexPath.item];
    if (self.layout) {
        GYStoreAllVerCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYStoreAllVerCell" owner:nil options:nil] firstObject];
        
        return CGSizeMake((ScreenWidth-5)/2, [cell height:model]);
    }else {
        GYStoreAllHorCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"GYStoreAllHorCell" owner:nil options:nil] firstObject];
        
        return CGSizeMake(ScreenWidth, [cell height:model]);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GYSearchGoos *model = self.goodsList[indexPath.item];
    GYShopHomeViewController *shopHomeVC = [[GYShopHomeViewController alloc] init];
    shopHomeVC.goods_id = model.goods_id;
    [self.navigationController pushViewController:shopHomeVC animated:YES];
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeadViewIdentifier forIndexPath:indexPath];
        headView.backgroundColor = [UIColor clearColor];
        UIButton *btu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, headView.height)];
        [btu setTitle:@"筛选" forState:UIControlStateNormal];
        [btu addTarget:self action:@selector(priceScreen) forControlEvents:UIControlEventTouchUpInside];
        btu.titleLabel.font = [UIFont systemFontOfSize:12];
        [btu setTitleColor:RGBColor(136, 136, 136) forState:UIControlStateNormal];
        [headView addSubview:btu];
        
        return headView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(ScreenWidth, 40);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.layout ? 5 : 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.layout ? 5 : 0;
}

- (void)priceScreen {
    
    GYPriceScreenViewController *priceScreenVC = [[GYPriceScreenViewController alloc] initWithNibName:@"GYPriceScreenViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    priceScreenVC.shopPriceScreenCallBack = ^(NSString *minPrice, NSString *maxPrice) {
        [weakSelf.goodsList removeAllObjects];
        weakSelf.currentPage = 1;
        weakSelf.hasmore = YES;
        //根据价格来筛选商品
        [weakSelf loadStoreAllGoods:[NSString stringWithFormat:@"%zd",weakSelf.currentPage] page:COUNT stc_id:@"" keyword:self.keyworld key:@"" order:@"" price_from:minPrice price_to:maxPrice];
    };
    [self.navigationController pushViewController:priceScreenVC animated:YES];
}

#pragma mark -- 懒加载

- (NSMutableArray *)goodsList {
    if (!_goodsList) {
        _goodsList = [NSMutableArray array];
    }
    
    return _goodsList;
}



@end
